from django.db import models
from django.utils import timezone
from .client import ZXClient


class OrderRefundManager(models.Manager):
    def create_refund(self, oldOriginSerialNo, oldOriginTranTime, cashAmount, installment):
        """
        :param oldOriginSerialNo: 支付商户订单号
        :param oldOriginTranTime: 商户支付时间
        :return:
        """
        params, response = ZXClient().refund_order(oldOriginSerialNo, oldOriginTranTime, cashAmount, installment)
        originSerialNo = params.get("msgBody").get("originSerialNo")
        originTranTime = params.get("msgBody").get("originTranTime")
        instance = self.create(
            merOrderId=oldOriginSerialNo,
            out_refund_no=originSerialNo,
            orderDatetime=originTranTime,
            installment=installment,
        )
        instance.errMsg = response.get("msgBody").get("retMsg")
        instance.errCode = response.get("msgBody").get("retCode")
        instance.status = response.get("msgBody").get("tranResult")
        instance.refundDatetime = response.get("msgBody").get("trxTime")
        instance.save()
        return instance


# 退款记录
class OrderRefund(models.Model):
    # requests
    merOrderId = models.CharField(max_length=64, verbose_name="支付时的订单号", db_index=True)
    out_refund_no = models.CharField(max_length=24, verbose_name="商户退款订单号（对应订单退款表）", blank=True, null=True)
    orderDatetime = models.DateTimeField(verbose_name="申请退款时间")
    installment = models.CharField(verbose_name="分期数(支付后返回)", max_length=2, blank=True, null=True)
    # response
    errMsg = models.CharField(verbose_name="返回信息", max_length=256, blank=True, null=True)
    errCode = models.CharField(verbose_name="平台错误码", blank=True, null=True, max_length=256)
    status = models.CharField(verbose_name="交易状态", max_length=32)
    refundDatetime = models.DateTimeField(verbose_name="退款受理时间", blank=True, null=True)
    objects = OrderRefundManager()

    class Meta:
        verbose_name = "中信银行退款记录"
        verbose_name_plural = verbose_name


class OrderRecordManager(models.Manager):
    def get_order_record_instance(self, out_trade_no):
        return self.get(out_trade_no=out_trade_no)


class OrderRecord(models.Model):
    srcReserve = models.CharField(max_length=16, verbose_name="附加信息", help_text="附加信息")
    originMerId = models.CharField(max_length=15, verbose_name="商户号")
    requestTimestamp = models.DateTimeField(verbose_name="请求时间")
    out_trade_no = models.CharField(verbose_name="商户订单号, 对应SupplyOrder.out_trade_no", db_index=True, max_length=64)
    goodsAmount = models.IntegerField(verbose_name="商品数量", default=1)
    # response
    orderKey = models.CharField(db_index=True, max_length=64, verbose_name="订单key，用于后续的支付等操作", blank=True, null=True)
    errMsg = models.CharField(verbose_name="返回信息", max_length=256, blank=True, null=True)
    errCode = models.CharField(verbose_name="平台错误码", blank=True, null=True, max_length=256)
    totalAmount = models.IntegerField(verbose_name="订单金额", blank=True, null=True, help_text="以分为单位")
    createTime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    installment = models.CharField(verbose_name="分期数(支付后返回)", max_length=2, blank=True, null=True)
    # 异步通知
    serialNo = models.CharField(verbose_name="银行订单号", blank=True, null=True, db_index=True, max_length=64)
    status = models.CharField(verbose_name="交易状态", max_length=32, blank=True, null=True, db_index=True)
    objects = OrderRecordManager()

    class Meta:
        verbose_name = "中信银行支付记录"
        verbose_name_plural = verbose_name

    def update_response(self, **kwargs):
        """
        按下单请求返回数据更新结果
        :return:
        """
        self.orderKey = kwargs.get("orderKey")
        self.errCode = kwargs.get("retCode")
        self.errMsg = kwargs.get("retMsg")
        self.save()
        return self

    def update_search_response(self, **kwargs):
        self.status = kwargs.get("tranResult")
        self.serialNo = kwargs.get("tranSerialNo")
        self.errMsg = kwargs.get("retMsg")
        self.errCode = kwargs.get("retCode")
        self.installment = kwargs.get("installment")
        self.save()


class ZXUser(models.Model):
    zx_user_id = models.CharField(db_index=True, verbose_name="中信银行用户唯一标识", max_length=64)
    create_time = models.DateTimeField(verbose_name="创建时间", default=timezone.now)

    class Meta:
        verbose_name = "中信用户"
        verbose_name_plural = verbose_name
